package com.ubxtech.elasticsearch.config;

import cn.hutool.core.util.StrUtil;
import com.ubxtech.core.utils.StrPool;
import com.ubxtech.elasticsearch.properties.CustomElasticsearchProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.elc.ReactiveElasticsearchConfiguration;
import org.springframework.data.elasticsearch.support.HttpHeaders;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 *
 * @author Victor.Xiao
 * @since 2023-08-09 15:25
*/
@Configuration
@Slf4j
@EnableConfigurationProperties(CustomElasticsearchProperties.class)
@ConditionalOnProperty(prefix = CustomElasticsearchProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class CustomElasticsearchConfig extends ReactiveElasticsearchConfiguration {

    @Resource
    private CustomElasticsearchProperties customElasticsearchProperties;

    @Resource
    private ElasticsearchProperties elasticsearchProperties;

    @Override
    public ClientConfiguration clientConfiguration() {
        List<String> uris = elasticsearchProperties.getUris();
        boolean ssl = uris.get(0).toLowerCase().startsWith(StrPool.HTTPS);
        uris = uris.stream().map(a -> a.toLowerCase().replaceAll(StrPool.HTTPS_PREFIX,"").replaceAll(StrPool.HTTP_PREFIX,"")).toList();
        ClientConfiguration.MaybeSecureClientConfigurationBuilder maybeSecureClientConfigurationBuilder = ClientConfiguration.builder().connectedTo(uris.toArray(new String[0]));
        if (ssl) {
            maybeSecureClientConfigurationBuilder.usingSsl();
        }
        if (StrUtil.isNotBlank(elasticsearchProperties.getUsername()) && StrUtil.isNotBlank(elasticsearchProperties.getPassword())) {
            maybeSecureClientConfigurationBuilder.withBasicAuth(elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword());
        }
        maybeSecureClientConfigurationBuilder
                .withConnectTimeout(elasticsearchProperties.getConnectionTimeout())
                .withSocketTimeout(elasticsearchProperties.getSocketTimeout())
                .withHeaders(() -> {
                    HttpHeaders headers = new HttpHeaders();
                    headers.add("currentTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                    return headers;
                });
        return maybeSecureClientConfigurationBuilder.build();
    }
}
